import axios from 'axios'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
// 1. 利用axios的方法create创建axios实例
const requests = axios.create({
  // 配置对象
  baseUrl: '/api',
  // 超时时间
  timeout: 5000
})

// 请求拦截器

requests.interceptors.request.use((config) => {
  // config 配置对象，对象里面的header请求头很重要
  if (store.state.token) {
    config.headers.Authorization = 'Bearer ' + store.state.token
  }

  store.commit('setLoading', true)
  store.commit('setError', { state: false, message: '' })
  // if (store.state.uuid_token) {
  //   config.headers.userTempId = store.state.uuid_token
  // }
  // config.params = { ...config.params, icode: 'C6A6C4086133360B' }
  nProgress.start()
  return config
})

// 相应拦截器
requests.interceptors.response.use(
  (res) => {
    // 成功
    setTimeout(() => {
      store.commit('setLoading', false)
    }, 500)
    store.commit('setError', {
      state: false
    })
    nProgress.done()
    return res.data
  }, (error) => {
    // 失败
    setTimeout(() => {
      store.commit('setLoading', false)
    }, 500);
    store.commit('setError', {
      state: true,
      message: error.response.data.error
    })
    console.log(error.response.data.error)
    return Promise.reject(new Error(error))
  })

export default requests
